package com.bonc.modules.job.task;

import cn.hutool.core.util.ObjectUtil;
import com.bonc.common.utils.SftpUtils;
import com.bonc.modules.rpt.entity.ArcInfoAudio;
import com.bonc.modules.rpt.entity.ArcInfoAudioDealTime;
import com.bonc.modules.rpt.service.ArcInfoAudioDealTimeService;
import com.bonc.modules.rpt.service.ArcInfoAudioService;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;

@Slf4j
@Component("arcInfoAudioTask")
public class ArcInfoAudioTask implements ITask {

    @Autowired
    private ArcInfoAudioService arcInfoAudioService;

    @Autowired
    private ArcInfoAudioDealTimeService arcInfoAudioDealTimeService;

    /** SFTP 登录用户名*/
    @Value("${audio.sftp.username}")
    private String sftpUsername;

    /** SFTP 登录密码*/
    @Value("${audio.sftp.password}")
    private String sftpPassword;

    /** SFTP 服务器地址IP地址*/
    @Value("${audio.sftp.host}")
    private String sftpHost;

    /** SFTP 端口*/
    @Value("${audio.sftp.port}")
    private String sftpPort;

    /** SFTP 音频保存路径*/
    @Value("${audio.sftp.audioDir}")
    private String sftpAudioDir;

    /** SFTP 音频保存路径*/
    @Value("${audio.sftp.filenameEncode}")
    private String sftpFilenameEncode;

    @Override
    public void run(String params) throws Exception {

        Session session = null;
        ChannelSftp channelSftp = null;
        List<ArcInfoAudioDealTime> arcInfoAudioDealTimeList = arcInfoAudioDealTimeService.list();
        final Long timeStamp;
        if(ObjectUtil.isNotEmpty(arcInfoAudioDealTimeList)){
            timeStamp = arcInfoAudioDealTimeList.get(0).getTimeStamp();
            log.debug("ArcInfoAudioTask : Get arcInfoAudioDealTimeStamp : " + timeStamp);
        } else {
            timeStamp = null;
            log.debug("ArcInfoAudioTask : Get arcInfoAudioDealTimeStamp is null ");
        }

        try {
            session = SftpUtils.getSftpSession(sftpHost, Integer.parseInt(sftpPort), sftpUsername, sftpPassword);
            if(session != null){
                channelSftp = SftpUtils.getChannelSftp(session);
            }
            if(channelSftp != null){
                if(ObjectUtil.isNotEmpty(sftpFilenameEncode)) {
                    channelSftp.setFilenameEncoding(sftpFilenameEncode);
                }
                String pathPattern = sftpAudioDir;
                boolean endAppend = !sftpAudioDir.endsWith("/");
                if(endAppend){
                    pathPattern += "/";
                }
                final String pathDir = pathPattern;
                pathPattern += ("*");

                Vector<ChannelSftp.LsEntry> fileVector = channelSftp.ls(pathPattern);
                List<ArcInfoAudio> audioFileList = fileVector.stream().filter(e-> {
                    if(!e.getFilename().toLowerCase().endsWith(".mp3")){
                        return false;
                    }
                    if(timeStamp == null){
                        return true;
                    }
                    if(e.getAttrs().getMTime() > timeStamp){
                        return true;
                    }
                    return false;
                }).map(e -> {
                    ArcInfoAudio arcInfoAudio = new ArcInfoAudio();
                    arcInfoAudio.setAudioPath(pathDir + e.getFilename());
                    arcInfoAudio.setMTime(Long.valueOf(e.getAttrs().getMTime()));
                    arcInfoAudio.setModifyTime(new Date(Long.valueOf(e.getAttrs().getMTime())));
                    int index = e.getFilename().indexOf("_");
                    if(index >= 0){
                        arcInfoAudio.setCaseNo(e.getFilename().substring(0, index));
                    }
                    if(ObjectUtil.isNotEmpty(arcInfoAudio.getCaseNo()) && ObjectUtil.isNotEmpty(arcInfoAudio.getAudioPath())){
                        return arcInfoAudio;
                    }
                    return null;
                }).filter(e -> e != null).collect(Collectors.toList());
                if(ObjectUtil.isNotEmpty(audioFileList)) {
                    log.debug("ArcInfoAudioTask : Save ArcInfoAudioList. size : " + audioFileList.size());
                    arcInfoAudioService.saveArcInfoAudioList(audioFileList);
                    log.debug("ArcInfoAudioTask : Save Success ArcInfoAudioList. size : " + audioFileList.size());
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
            log.debug("ArcInfoAudioTask : " + e.getMessage());
        } finally {
            log.debug("ArcInfoAudioTask : Disconnect sftp channel");
            if(channelSftp != null){
                channelSftp.disconnect();
            }
            log.debug("ArcInfoAudioTask : Disconnect sftp session");
            if(session != null){
                session.disconnect();
            }
        }
    }
}
